import { defineStore } from "pinia";
import APIKEYAPI, {
  type ApiKeyType,
  type ApiKeyForm,
  type ApiKeyListParams,
} from "@/api/system/api-key";
import { ref } from "vue";
import { store } from "@/store";

export const useApiKeyStore = defineStore("apiKey", () => {
  const list = ref<ApiKeyType[]>([]);
  const totalCount = ref(0);
  const totalPage = ref(0);
  const loading = ref({
    list: false,
    submit: false,
  });

  async function fetchList(params: ApiKeyListParams) {
    loading.value.list = true;
    try {
      const res = await APIKEYAPI.getApiKeyList(params);
      list.value = res.records;
      totalCount.value = res.total_count;
    } finally {
      loading.value.list = false;
    }
  }

  async function fetchAdd(data: ApiKeyForm) {
    loading.value.submit = true;
    try {
      await APIKEYAPI.addApiKey(data);
    } finally {
      loading.value.submit = false;
    }
  }

  async function fetchUpdate(data: Partial<ApiKeyForm>) {
    loading.value.submit = true;
    try {
      await APIKEYAPI.updateApiKey(data);
    } finally {
      loading.value.submit = false;
    }
  }

  async function fetchDelete(id: number) {
    await APIKEYAPI.deleteApiKey(id);
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchList,
    fetchAdd,
    fetchUpdate,
    fetchDelete,
  };
});

export const useApiKeyStoreHook = () => {
  return useApiKeyStore(store);
};
